//
//  ZLPullMenu.m
//  ZLPullMenu
//
//  Created by 科大 on 2024/5/27.
//

#import "ZLPullMenu.h"
#import "ZLPullMenuCell.h"
#import "ZLPullMenuContentView.h"
#import <Masonry/Masonry.h>

@interface ZLPullMenu()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ZLPullMenuContentViewDelegate>
/// 列表
@property (nonatomic, strong) UICollectionView *collectionView;
/// 布局
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
/// 显示菜单
@property (nonatomic, strong) ZLPullMenuContentView *menuView;
/// 选中菜单下标
@property (nonatomic, assign) NSInteger selectedIndex;
/// 背景
@property (nonatomic, strong) UIView *bottomView;
/// 背景
@property (nonatomic, strong) UIView *topView;
@end

@implementation ZLPullMenu

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
    }
    return self;
}

- (void)setInsets:(UIEdgeInsets)insets {
    [self.collectionView setContentInset:insets];
}

- (void)setInterval:(CGFloat)interval {
    self.layout.minimumLineSpacing = interval;
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
}

- (void)reloadData {
    [self.collectionView reloadData];
    for (ZLPullMenuItem *item in self.menus) {
        if (item.selected) {
            [self.menuView reloadData:item.groups];
            break;
        }
    }
}

#pragma mark - action

- (void)closeAction {
    for (ZLPullMenuItem *item in self.menus) {
        item.selected = NO;
    }
    [self closeMenu];
}

- (void)openMenu {
    [self.collectionView reloadData];
    UIWindow * window = [UIApplication sharedApplication].windows.lastObject;
    CGRect rect = [self convertRect:self.bounds toView:window];
    self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(rect), window.frame.size.width, window.frame.size.height - CGRectGetMaxY(rect));
    self.topView.frame = CGRectMake(0, 0, window.frame.size.width, CGRectGetMinY(rect));
    self.menuView.frame = CGRectMake(0, CGRectGetMaxY(rect), window.frame.size.width, 0);
    [window addSubview:self.bottomView];
    [window addSubview:self.topView];
    [window addSubview:self.menuView];
    [UIView animateWithDuration:0.1 animations:^{
        self.bottomView.alpha = 1;
        CGFloat maxHeight = MIN(window.frame.size.height - CGRectGetMaxY(rect), [self.menuView getMenuHeight]);
        self.menuView.frame = CGRectMake(0, CGRectGetMaxY(rect), window.frame.size.width, maxHeight);
    }];
}

- (void)closeMenu {
    [self.bottomView removeFromSuperview];
    [self.topView removeFromSuperview];
    [self.collectionView reloadData];
    [UIView animateWithDuration:0.1 animations:^{
        self.bottomView.alpha = 0;
        self.menuView.frame = CGRectMake(0, CGRectGetMinY(self.menuView.frame), CGRectGetWidth(self.menuView.frame), 0);
    } completion:^(BOOL finished) {
        [self.menuView removeFromSuperview];
    }];
}

#pragma mark - ZLPullMenuContentViewDelegate

- (BOOL)pullMenuContentViewWillSelected:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(pullMenuWillSelected:)]) {
        ZLIndexPath *zindexPath = [ZLIndexPath indexPath:self.selectedIndex groupIndex:indexPath.section optionIndex:indexPath.row];
        return [self.delegate pullMenuWillSelected:zindexPath];
    }
    return YES;
}

- (void)pullMenuContentViewDidSelected:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(pullMenuDidSelected:)]) {
        ZLIndexPath *zindexPath = [ZLIndexPath indexPath:self.selectedIndex groupIndex:indexPath.section optionIndex:indexPath.row];
        [self.delegate pullMenuDidSelected:zindexPath];
    }
}

#pragma mark - delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.menus.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPullMenuItem *item = self.menus[indexPath.row];
    switch (self.layoutMode) {
        case ZLPullMenuLayoutDefault: {
            CGFloat width = [item.menuTitle boundingRectWithSize:CGSizeMake(1000, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.width;
            [self.collectionView setContentInset:UIEdgeInsetsMake(0, 5, 0, 5)];
            self.layout.minimumLineSpacing = 10;
            return CGSizeMake(width + 15, self.frame.size.height);
        }
        case ZLPullMenuLayoutCenter: {
            CGFloat width = self.frame.size.width / self.menus.count;
            [self.collectionView setContentInset:UIEdgeInsetsZero];
            self.layout.minimumLineSpacing = 0;
            return CGSizeMake(width, self.frame.size.height);
        }
        default:
            return CGSizeZero;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPullMenuItem *item = self.menus[indexPath.row];
    ZLPullMenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZLPullMenuCell" forIndexPath:indexPath];
    cell.item = item;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPullMenuItem *tapItem = self.menus[indexPath.row];
    [self.menuView reloadData:tapItem.groups];
    self.selectedIndex = -1;
    for (ZLPullMenuItem *item in self.menus) {
        if (item != tapItem) {
            item.selected = NO;
            continue;
        }
        if (item.selected) {
            item.selected = NO;
            [self closeMenu];
        } else {
            item.selected = YES;
            self.selectedIndex = indexPath.row;
            [self openMenu];
        }
    }
}

#pragma mark - init

- (ZLPullMenuContentView *)menuView {
    if (!_menuView) {
        _menuView = [[ZLPullMenuContentView alloc] initWithFrame:CGRectMake(0, self.frame.size.height, self.frame.size.width, 0)];
        _menuView.layer.masksToBounds = YES;
        _menuView.delegate = self;
    }
    return _menuView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[ZLPullMenuCell class] forCellWithReuseIdentifier:@"ZLPullMenuCell"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout {
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.minimumLineSpacing = 0;
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _layout;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        _bottomView.alpha = 0;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeAction)];
        [_bottomView addGestureRecognizer:tap];
    }
    return _bottomView;
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeAction)];
        [_topView addGestureRecognizer:tap];
    }
    return _topView;
}

@end
